package com.liucxu.jiandanl.Config;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.liucxu.jiandanl.R;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

/**
 * 基于ImageLoader的图片加载类
 * Created by liuchenxu on 2016/8/5.
 */
public class ImageLoaderUtils {
    private static final int MAX_DISK_CACHE = 1024 * 1024 * 50;
    private static final int MAX_MEMORY_CACHE = 1024 * 1024 * 10;
    private static ImageLoader imageLoader;

    public static void displayImageWithLoadingPicture(String url, ImageView target) {
        if (imageLoader == null) {
            imageLoader = ImageLoader.getInstance();
        }
        imageLoader.displayImage(url, target, initImageLoaderOptions());
    }

    /**
     * 初始化ImageLoader
     */
    private static DisplayImageOptions initImageLoaderOptions() {
        return new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisc(true)
                .bitmapConfig(Bitmap.Config.ARGB_8888)
                .resetViewBeforeLoading(true)
                .showImageOnLoading(R.drawable.ic_loading_large)
                .showImageForEmptyUri(R.drawable.ic_loading_large)
                .showImageOnFail(R.drawable.ic_loading_large)
                .build();

    }

    private static ImageLoader getImageLoader() {
        if (imageLoader == null) {
            synchronized (ImageLoaderUtils.class) {
                imageLoader = ImageLoader.getInstance();
            }
        }
        return imageLoader;
    }

    /**
     * @param context
     */
    public static void initImageLoader(Context context) {
        ImageLoaderConfiguration.Builder build = new ImageLoaderConfiguration.Builder(context);
        build.tasksProcessingOrder(QueueProcessingType.LIFO);
        build.discCacheSize(MAX_DISK_CACHE);
        build.memoryCacheSize(MAX_MEMORY_CACHE);
        build.memoryCache(new LruMemoryCache(MAX_MEMORY_CACHE));
        getImageLoader().init(build.build());
    }
}
